<script setup lang="ts">
import {
  useMessage,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NIcon,
  NDatePicker,
  NSelect,
  NImage,
  type DataTableColumns,
  NDataTable,
  NTreeSelect,
  NInputNumber,
  type SelectOption,
  type UploadFileInfo,
  NFlex,
  NTooltip
} from 'naive-ui'
import { ref, shallowRef, h, onMounted, reactive, computed } from 'vue'
import type { IdentifyInfoModel, IEOptionModel, CommonSelectOptionModel } from '@/api/batch'
import type { BatchIdentifyItemModel } from '@/api/batchV2'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { ArrowRightAltFilled } from '@vicons/material'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import type { BatchDetailModel } from '@/api/batchV2'
import type { DicTreeModel } from '@/api/dic'
import VBackImg from '@/assets/images/back.png'
import FileList from '@/components/FileList.vue'
import VAttachments from '@/views/OA/Common/Attachments.vue'
import BatchCres from './components/BatchCres.vue'

const route = useRoute()
const router = useRouter()
const routeReplace = useRouteReplace(route.query.redirect as string)
const message = useMessage()

const processInfo = ref(
  {} as {
    finish: boolean
    register: boolean
    submit: boolean
  }
)
const process = async (id: number) => {
  const [error, res] = await sendRequest({
    module: 'batch',
    api: 'identifyProcess',
    override: {
      params: {
        batchId: route.params.id,
        identifyId: id || null
      }
    }
  })
  if (error) throw error
  if (res.code !== 0) throw new Error(res.msg)
  processInfo.value = res.data
}

const fileList = ref<UploadFileInfo[]>([])
const identifyInfo = ref({} as IdentifyInfoModel)
const identifyExpertIds = computed(() => {
  const ids = identifyInfo.value.identifyExpertIds
  return ids ? ids.split(',') : null
})
const queryIdentifyInfo = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<IdentifyInfoModel>>({
      module: 'batch',
      api: 'identifyLast',
      override: {
        params: {
          batchId: route.params.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    fileList.value = await queryFileList(res.data.fileIds)
    identifyInfo.value = res.data
    process(res.data.id)
  } catch (error) {
    console.error(error)
  }
}

const queryFileList = async (filesIds: string): Promise<UploadFileInfo[]> => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    return res.data.map((e) => ({
      path: e.path,
      id: e.id,
      name: e.name,
      status: 'finished',
      url: e.path,
      type: e.type
    }))
  } catch (error) {
    return []
  }
}

const clueSelectOptions = ref<SelectOption[]>([])
const clueSelectLoading = ref(false)
const queryClueSelectOptions = async () => {
  clueSelectLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'batchV2',
      api: 'clueList'
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    clueSelectLoading.value = false
  }
}

const clueMethodOptions = reactive<DicTreeModel[]>([])
const clueMethodLoading = ref(false)
const queryClueMethodOptions = async () => {
  clueMethodLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: 'A30'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueMethodOptions.length = 0
    clueMethodOptions.push(...(res.data[0] ? res.data[0].children || [] : []))
  } catch (error) {
    console.error(error)
  } finally {
    clueMethodLoading.value = false
  }
}

const collectorName = ref<string | null>(null)
const batchFileList = ref<UploadFileInfo[]>([])
const batchInfo = ref({} as BatchDetailModel)
const isJCDG = computed(() => batchInfo.value.solicitMethodCode === 'A3007')
const queryBatchInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<BatchDetailModel>>({
    module: 'batchV2',
    api: 'detail',
    override: {
      params: {
        id: route.params.id
      }
    }
  })
  if (error) return message.error(error.message)

  sendRequest({
    module: 'clue',
    api: 'infoManage',
    uri: {
      id: res.data.clueId
    }
  })
    .then(([_, cr]) => {
      if (cr) {
        sendRequest({
          module: 'collector',
          api: 'info',
          uri: {
            id: cr.data.collectorId
          }
        })
          .then(([_, er]) => {
            if (er) collectorName.value = er.data.userName
          })
          .catch(() => (collectorName.value = null))
      }
    })
    .catch(() => (collectorName.value = null))

  if (res.data.endTime) {
    res.data.endTime = res.data.endTime.slice(0, 10)
  }
  if (res.data.startTime) {
    res.data.startTime = res.data.startTime.slice(0, 10)
  }
  if (res.data.solicitNum) {
    res.data.solicitNum = Number(res.data.solicitNum)
  }
  batchInfo.value = res.data
  if (res.data.fileIds) batchFileList.value = await queryFileList(res.data.fileIds)
}

const ieSelectOptions = shallowRef<IEOptionModel[]>([])
const ieLoading = ref(false)
const queryIESelectOptions = async () => {
  try {
    ieLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<IEOptionModel[]>>({
      module: 'batch',
      api: 'ieSelect'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    ieSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    ieLoading.value = false
  }
}

const itSelectOptions = shallowRef<CommonSelectOptionModel[]>([])
const itLoading = ref(false)
const queryITSelectOptions = async () => {
  try {
    itLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<CommonSelectOptionModel[]>>({
      module: 'batch',
      api: 'itSelect'
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    itSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    itLoading.value = false
  }
}

const tableData = ref<BatchIdentifyItemModel[]>([])
const tableLoading = ref(false)
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<BatchIdentifyItemModel>>({
      module: 'batchV2',
      api: 'identifyItems',
      override: {
        params: {
          batchId: route.params.id,
          limit: 100000000
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    res.data.list.forEach((e) => (e.subItemCode = e.itemCode))
    res.data.list.forEach((e) => (e.subItemId = e.itemId))
    tableData.value = res.data.list

    tableData.value.forEach((item) => {
      if (!item.imageIds) return
      sendRequest({
        module: 'upload',
        api: 'list',
        override: {
          params: {
            ids: item.imageIds
          }
        }
      }).then(([error, res]) => {
        if (error || res.code !== 0) return
        item._imageFiles = res.data
      })
    })
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}
const columns: DataTableColumns<BatchIdentifyItemModel> = [
  // {
  //   title: '序号',
  //   key: 'index',
  //   width: 80,
  //   align: 'center',
  //   render: (e, index) => {
  //     if (!e.subItems || e.subItems.length === 0) return index + 1
  //     return index + 1
  //   }
  // },
  {
    title: '名称',
    key: 'itemName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: '年代',
    key: 'years'
  },
  {
    title: '备注',
    key: 'remark'
  },
  {
    title: '图片',
    key: 'imageIds',
    render({ _imageFiles }) {
      if (!_imageFiles) return
      return h(
        NFlex,
        {},
        {
          default: () =>
            _imageFiles.map((e) =>
              h(NImage, {
                src: e.path,
                width: 50
              })
            )
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    render: (e) => [
      h(
        NButton,
        {
          color: '#6CB187',
          quaternary: true,
          size: 'small',
          style: {
            display: e.subItems?.length ? 'none' : 'inline-flex'
          },
          onClick: () => {
            router.push({
              name: 'detailBatchItem',
              params: {
                id: route.params.id,
                itemId: e.itemId
              },
              query: {
                type: 'r',
                redirect: route.fullPath
              }
            })
          }
        },
        { default: () => '详情' }
      )
    ]
  }
]
onMounted(() => {
  queryClueSelectOptions()
  queryClueMethodOptions()
  queryIESelectOptions()
  queryITSelectOptions()
  queryIdentifyInfo()
  queryBatchInfo()
  queryTableData()
})
</script>

<template>
  <div class="batch-identified">
    <div class="ia-title">鉴定流程</div>
    <div class="ia-card identity-flow">
      <div
        class="step"
        :class="{ finished: processInfo.submit }"
      >
        提交鉴定
      </div>
      <NIcon
        color="#6CB187"
        size="32"
      >
        <ArrowRightAltFilled />
      </NIcon>
      <div
        class="step"
        :class="{ finished: processInfo.register }"
      >
        鉴定登记
      </div>
      <NIcon
        color="#6CB187"
        size="32"
      >
        <ArrowRightAltFilled />
      </NIcon>
      <div
        class="step"
        :class="{ finished: processInfo.finish }"
      >
        鉴定结束
      </div>
    </div>

    <div class="br"></div>

    <div class="ia-title">鉴定信息</div>
    <NForm
      disabled
      label-placement="left"
      require-mark-placement="left"
      :show-feedback="false"
      :show-require-mark="false"
      label-width="100rem"
      class="ia-card grid"
    >
      <NFormItem label="鉴定名称：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyName"
        />
      </NFormItem>
      <NFormItem label="鉴定日期：">
        <NDatePicker
          input-readonly
          placeholder="/"
          style="flex: 1"
          format="yyyy-MM-dd"
          :formatted-value="identifyInfo.identifyTime"
        />
      </NFormItem>
      <NFormItem label="鉴定地点：">
        <NInput
          placeholder="/"
          :value="identifyInfo.identifyAddress"
        />
      </NFormItem>
      <NFormItem label="鉴定类型：">
        <NSelect
          :options="(itSelectOptions as unknown as SelectOption[])"
          label-field="name"
          placeholder="/"
          :value="identifyInfo.identifyTypeCode"
        />
      </NFormItem>
      <NFormItem label="鉴定专家：">
        <NSelect
          :options="(ieSelectOptions as unknown as SelectOption[])"
          multiple
          label-field="userName"
          value-field="id"
          placeholder="/"
          :value="identifyExpertIds"
        />
      </NFormItem>
      <NFormItem label="描述：">
        <NInput
          type="textarea"
          rows="1"
          placeholder="/"
          :value="identifyInfo.identifyDescription"
        />
      </NFormItem>
      <NFormItem label="附件：">
        <FileList :file-list="fileList" />
      </NFormItem>
    </NForm>

    <div class="br"></div>

    <div class="ia-title">批次信息</div>
    <DetailFormProvider>
      <NForm
        disabled
        label-placement="left"
        label-width="100rem"
        :show-feedback="false"
        :show-require-mark="false"
        class="ia-card form"
      >
        <NFormItem label="关联线索：">
          <NSelect
            :value="batchInfo.clueId"
            :options="clueSelectOptions"
            :loading="clueSelectLoading"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="批次名称：">
          <NTooltip :max-width="350">
            <template #trigger>
              <NInput
                :value="batchInfo.name"
                placeholder="/"
              />
            </template>
            {{ batchInfo.name }}
          </NTooltip>
        </NFormItem>
        <NFormItem label="征集方式：">
          <NTreeSelect
            :value="batchInfo.solicitMethodCode"
            :options="clueMethodOptions"
            :loading="clueMethodLoading"
            placeholder="/"
            key-field="code"
            label-field="name"
          />
        </NFormItem>
        <NFormItem label="接收时间：">
          <NDatePicker
            :formatted-value="batchInfo.receiveTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="接收人：">
          <NInput
            :value="batchInfo.receiver"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="征集数量：">
          <NInputNumber
            :value="batchInfo.solicitNum"
            placeholder="/"
            :show-button="false"
            :min="0"
            :max="Number.MAX_SAFE_INTEGER"
          />
        </NFormItem>
        <NFormItem label="证书发放：">
          <BatchCres :batch-id="batchInfo.id" />
        </NFormItem>
        <template v-if="isJCDG">
          <NFormItem label="开始时间：">
            <NDatePicker
              :formatted-value="batchInfo.startTime"
              type="date"
              placeholder="/"
            />
          </NFormItem>
          <NFormItem label="结束时间：">
            <NDatePicker
              :formatted-value="batchInfo.endTime"
              type="date"
              placeholder="/"
            />
          </NFormItem>
          <NFormItem label="代存期限：">
            <NInput
              :value="batchInfo.depositPeriod"
              placeholder="/"
            />
          </NFormItem>
        </template>

        <NFormItem label="藏家：">
          <NInput
            v-model:value="collectorName"
            placeholder="/"
            disabled
          />
        </NFormItem>
        <NFormItem label="移交人：">
          <NInput
            v-model:value="batchInfo.transferor"
            placeholder="/"
            disabled
            style="flex-shrink: 2"
          />
          <NInput
            v-model:value="batchInfo.transferorPhone"
            placeholder="/"
            disabled
          />
        </NFormItem>

        <NFormItem label="创建时间：">
          <NDatePicker
            :formatted-value="batchInfo.createTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="修改时间：">
          <NDatePicker
            :formatted-value="batchInfo.modifyTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="鉴定状态：">
          <NInput
            :value="batchInfo.identifyStatus"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem
          label="备注："
          class="n-form-item--textarea"
        >
          <NInput
            :value="batchInfo.remark"
            type="textarea"
            placeholder="/"
            rows="5"
          />
        </NFormItem>
        <NFormItem label="附件：">
          <VAttachments
            v-if="batchInfo.fileIds"
            :attach-list="batchFileList"
          />
        </NFormItem>
      </NForm>
    </DetailFormProvider>

    <div class="br"></div>

    <div class="ia-title">物品信息</div>
    <div class="ia-card">
      <NDataTable
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        children-key="subItems"
        max-height="500rem"
        bordered
      />
    </div>
  </div>

  <FixedAction>
    <div class="batch-identified-buttons">
      <NButton
        ghost
        @click="routeReplace"
        :style="`width: 78px; color: #5fb17f`"
      >
        <template #icon>
          <NImage
            :src="VBackImg"
            :style="`width: 50rem; height: 50rem`"
            preview-disabled
          ></NImage>
        </template>
        返回
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.batch-identified {
  min-height: 100%;
  padding: 15rem 0 110rem;
  background-color: #f0efee;

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .ia-card {
    padding: 20rem;
    background-color: #e1e1e1;

    &.form {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16rem 32rem;

      .n-form-item--textarea {
        grid-column: 1 / -1;
      }

      .n-date-picker,
      .n-input-number {
        flex: 1;
      }
    }
  }

  .n-form.grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rem 32rem;
  }

  .ia-title {
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }

  .identity-flow {
    display: flex;
    align-items: center;
    gap: 0 1.5em;

    .step {
      padding: 10rem 15rem;
      background-color: #e1e1e1;

      &.finished {
        color: #fff;
        background-color: #6cb187;
      }
    }
  }
}

.batch-identified-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>
